package com.ruoyi.client.fxiaoke.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;

/**
 * 加解密工具类
 * 
 * @author huanghp
 * @date 2015年8月28日
 */
/**
 * 加解密工具类
 * 
 * @author 官宇
 * @date 2020-05-19
 */
public class SigUtils {
    private SigUtils() {}

    /**
     * 解密
     * @param ciphertext decode加密密文
     * @param aesKey decode 秘钥
     * @return
     */
    public static String aesDecrypt(String ciphertext, String aesKey) {
		byte[] ciphertextBytes = Base64.decodeBase64(ciphertext); // decode加密密文结果
		byte[] aesKeyBytes = Base64.decodeBase64(aesKey); // decode 秘钥
		SecretKeySpec keySpec = new SecretKeySpec(aesKeyBytes, "AES");
		IvParameterSpec iv = new IvParameterSpec(aesKeyBytes, 0, 16); // 初始化向量
		byte[] plaintextBytes;
		try {
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // 加密模式为CBC
			cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
			plaintextBytes = cipher.doFinal(ciphertextBytes);
		} catch (Exception e) {           
			e.printStackTrace();
			return null;
		}
		return new String(plaintextBytes, Charsets.UTF_8); // 指定UTF-8字符集
	}
    
    /**
     * 加密
     * @param plaintext
     * @param aesKey
     * @return
     */
    public static String aesEncrypt(String plaintext, String aesKey) {
        byte[] plaintextBytes = plaintext.getBytes();
        byte[] aesKeyBytes = Base64.decodeBase64(aesKey);
        SecretKeySpec keySpec = new SecretKeySpec(aesKeyBytes, "AES");
        IvParameterSpec iv = new IvParameterSpec(aesKeyBytes, 0, 16);
        byte[] encryptedBytes;
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
            encryptedBytes = cipher.doFinal(plaintextBytes);
        } catch (Exception e) {           
            return null;
        }
        return Base64.encodeBase64String(encryptedBytes); //转换为64位编码
}

}
